import { Peer, DataConnection } from 'peerjs';
import { useState, useEffect, useRef } from 'react';

const App = () => {
  const [peerId, setPeerId] = useState('');
  const [targetId, setTargetId] = useState('');
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState<Array<{text: string, from: string}>>([]);
  const [connection, setConnection] = useState<DataConnection | null>(null);
  const [connectionStatus, setConnectionStatus] = useState<'disconnected' | 'connecting' | 'connected'>('disconnected');
  const [error, setError] = useState<string>('');
  const peerInstance = useRef<Peer | null>(null);

  useEffect(() => {
    // 创建一个随机ID的Peer实例
    try {
      peerInstance.current = new Peer({
        host: 'localhost',
        port: 9000,
        path: '/myapp',
        debug: 2
      });

      // 当连接建立时获取ID
      peerInstance.current.on('open', (id) => {
        setPeerId(id);
        console.log('My peer ID is:', id);
        setError('');
      });

      // 监听接入的连接
      peerInstance.current.on('connection', handleConnection);

      // 错误处理
      peerInstance.current.on('error', (err) => {
        console.error('Peer error:', err);
        setError(`连接错误: ${err.message}`);
        setConnectionStatus('disconnected');
      });

      // 断开连接处理
      peerInstance.current.on('disconnected', () => {
        setConnectionStatus('disconnected');
        setError('与服务器断开连接');
      });

    } catch (err) {
      setError(`初始化错误: ${err}`);
    }

    return () => {
      if (connection) {
        connection.close();
      }
      peerInstance.current?.destroy();
    };
  }, []);

  const handleConnection = (conn: DataConnection) => {
    setConnectionStatus('connected');
    setError('');
    
    conn.on('data', (data) => {
      setMessages(prev => [...prev, { text: data as string, from: 'other' }]);
    });

    conn.on('close', () => {
      setConnectionStatus('disconnected');
      setConnection(null);
    });

    conn.on('error', (err) => {
      setError(`连接错误: ${err.message}`);
      setConnectionStatus('disconnected');
    });

    setConnection(conn);
  };

  const connectToPeer = () => {
    if (!peerInstance.current || !targetId) return;
    
    try {
      setConnectionStatus('connecting');
      const conn = peerInstance.current.connect(targetId);
      
      conn.on('open', () => {
        handleConnection(conn);
      });

      conn.on('error', (err) => {
        setError(`连接错误: ${err.message}`);
        setConnectionStatus('disconnected');
      });

    } catch (err) {
      setError(`连接失败: ${err}`);
      setConnectionStatus('disconnected');
    }
  };

  const disconnectPeer = () => {
    if (connection) {
      connection.close();
      setConnection(null);
      setConnectionStatus('disconnected');
    }
  };

  const sendMessage = () => {
    if (connection && message) {
      try {
        connection.send(message);
        setMessages(prev => [...prev, { text: message, from: 'me' }]);
        setMessage('');
        setError('');
      } catch (err) {
        setError(`发送消息失败: ${err}`);
      }
    }
  };

  return (
    <div style={{ padding: '20px', maxWidth: '600px', margin: '0 auto' }}>
      <h1>PeerJS 聊天Demo</h1>
      
      {error && (
        <div style={{ 
          padding: '10px', 
          backgroundColor: '#ffebee', 
          color: '#c62828', 
          borderRadius: '4px',
          marginBottom: '10px'
        }}>
          {error}
        </div>
      )}

      <div style={{ marginBottom: '20px' }}>
        <p>你的ID: {peerId}</p>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <input
            type="text"
            value={targetId}
            onChange={(e) => setTargetId(e.target.value)}
            placeholder="输入对方的ID"
            style={{ flexGrow: 1 }}
            disabled={connectionStatus === 'connected'}
          />
          {connectionStatus === 'disconnected' ? (
            <button 
              onClick={connectToPeer}
              disabled={!targetId}
            >
              连接
            </button>
          ) : (
            <button onClick={disconnectPeer}>
              断开连接
            </button>
          )}
        </div>
        <p style={{ 
          color: connectionStatus === 'connected' ? 'green' : 
                 connectionStatus === 'connecting' ? 'orange' : 'gray',
          fontSize: '14px'
        }}>
          状态: {
            connectionStatus === 'connected' ? '已连接' :
            connectionStatus === 'connecting' ? '连接中...' : '未连接'
          }
        </p>
      </div>

      <div style={{ 
        border: '1px solid #ccc', 
        padding: '10px', 
        height: '300px', 
        overflowY: 'auto',
        marginBottom: '10px',
        backgroundColor: '#f5f5f5'
      }}>
        {messages.map((msg, index) => (
          <div 
            key={index} 
            style={{
              textAlign: msg.from === 'me' ? 'right' : 'left',
              margin: '5px'
            }}
          >
            <span style={{
              background: msg.from === 'me' ? '#007bff' : '#6c757d',
              color: 'white',
              padding: '5px 10px',
              borderRadius: '10px',
              display: 'inline-block',
              maxWidth: '70%',
              wordBreak: 'break-word'
            }}>
              {msg.text}
            </span>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex' }}>
        <input
          type="text"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          placeholder="输入消息"
          style={{ flexGrow: 1, marginRight: '10px' }}
          onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
          disabled={connectionStatus !== 'connected'}
        />
        <button 
          onClick={sendMessage}
          disabled={connectionStatus !== 'connected'}
        >
          发送
        </button>
      </div>
    </div>
  );
};

export default App;